

/**
 * 通用js方法封装处理
 * Copyright (c) 2019 ruoyi
 */
(function ($) {
    var select = {
        options:new Map(),
    }
    axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

    // 创建axios实例
    const axiosRequest = axios.create({
        // 超时
        timeout: 10000,
    })

    // request拦截器
    axiosRequest.interceptors.request.use(
        (config) => {
            console.log("config----",config)
            openLoadingAndDisableButton()
            // get请求映射params参数
            if (config.method === 'get' && config.params) {
                let url = config.url + '?' + tansParams(config.params)
                url = url.slice(0, -1)
                config.params = {}
                config.url = url
            }else if( (config.method === 'post' || config.method ==='put') && config.data){
                // const contentType = config.headers['Content-Type']
                // const data = config.data
                // if(contentType.includes('application/json') && data instanceof Array){
                //     const keys = Object.keys(data).toString()
                //     if(keys == 'name,value'){
                //
                //     }
                // }
            }
            return config
        },
        (error) => {
            closeLoadingAndEnableButton()
            console.log(error)
            Promise.reject(error)
        },
    )

// 响应拦截器
    axiosRequest.interceptors.response.use(
        (res) => {
            closeLoadingAndEnableButton()
            // 未设置状态码则默认成功状态
            const code = res.data.code || web_status.SUCCESS
            // 获取错误信息
            const msg = errorCode[code] || res.data.msg || errorCode['default']
            // 二进制数据则直接返回
            if (
                res.request.responseType === 'blob' ||
                res.request.responseType === 'arraybuffer'
            ) {
                return res.data
            }
            if (code == web_status.WARNING) {
                $.modal.alertWarning(msg)
            } else if(code == web_status.FAIL){
                $.modal.alertError(msg);
                return Promise.reject(new Error(msg))
            }else if(code != web_status.SUCCESS){
                $.modal.alertError(msg);
                return Promise.reject('error')
            }else{
                return Promise.resolve(res.data)
            }
        },
        (error) => {
            closeLoadingAndEnableButton()
            console.log('err' + error)
            let { message } = error
            if (message == 'Network Error') {
                message = '后端接口连接异常'
            } else if (message.includes('timeout')) {
                message = '系统接口请求超时'
            } else if (message.includes('Request failed with status code')) {
                message = '系统接口' + message.substr(message.length - 3) + '异常'
            }

            $.modal.alertError(message);

            return Promise.reject(error)
        },
    )

    $.extend({
        operation:{
            //获取最大的排序值
            getIncrementWeight(params , name='weight') {
                $.axiosRequest.get(table.options.getIncrementWeightUrl,params)
                    .then(result=>{
                        const weight = result.data
                        $("[name="+name+"]").val(weight)
                    })
            }
            /**
             * 构建简单的select选择框
             * @param selectOptions select可选参数对象 其中 $select属性 必填
             * @param requestOptions 请求可选参数
             * @param callback 请求回调函数
             */
            ,buildSimpleSelect(selectOptions,requestOptions,callback){
                $.operation.getSimpleList(requestOptions)
                    .then(res=>{
                        if(callback instanceof Function){
                            callback(res)
                        }
                        /*判断 selectOptions是否为空 如果为空则不进行渲染*/
                        if(selectOptions && Object.keys(selectOptions).length>0){

                            if($.common.isString(selectOptions)){
                                const tagName = selectOptions
                                selectOptions = Object()
                                selectOptions["$select"] = $(tagName)
                                //Object.defineProperty(selectOptions,"$select",tagName)
                            }

                            selectOptions.data = res.data
                            $.selectComponent.init(selectOptions)
                        }
                    })
            },
            //获取简单的数据列表
            getSimpleList(options){
                const defaultOptions = {
                    prefix:null,
                    url:null,
                    method:'get',
                    params:{},
                    data:[],
                    callback:null,
                }
                const completeOptions = $.extend(defaultOptions,options)

                if(!completeOptions.url && completeOptions.prefix){
                    completeOptions.url = completeOptions.prefix+"/simpleList"
                }else if(!completeOptions.url){
                    completeOptions.url = table.options.simpleListUrl
                }
                const method = completeOptions.method
                const url = completeOptions.url

                if(method == 'get'){
                    return $.axiosRequest.get(url,completeOptions.params)
                }else if(method == 'post'){
                    return $.axiosRequest.post(url,completeOptions.data)
                }
            },
            //新增请求通用方法
            insert:function(url,data,callback){
                $.operation.save($.axiosRequest.post(url,data),callback , true)
                //修改请求通用方法
            },update:function(url,data,callback){
                $.operation.save($.axiosRequest.put(url,data),callback , true)
            },
            //状态修改样式通用工具方法
            stateTools(row) {
                const state = table.options.state
                if (row[state]==state_type.OK.value) {
                    return `<i class="fa fa-toggle-on text-info fa-2x" onclick="$.operation.handleStateChange('${row.id}',${state_type.DISABLE.value})"></i> `;
                }
                return `<i class="fa fa-toggle-off text-info fa-2x" onclick="$.operation.handleStateChange('${row.id}',${state_type.OK.value})"></i> `;
            },
            //批量修改状态为可用
            handleStateToAvailable(){
                table.set();
                var rows = $.common.isEmpty(table.options.uniqueId) ? $.table.selectFirstColumns() : $.table.selectColumns(table.options.uniqueId);

                $.operation.executionStateChange(rows,state_type.OK.value)
            },
            //批量修改状态为禁用
            handleStateToDisabled(){
                table.set();
                var rows = $.common.isEmpty(table.options.uniqueId) ? $.table.selectFirstColumns() : $.table.selectColumns(table.options.uniqueId);

                $.operation.executionStateChange(rows,state_type.DISABLE.value)
            },handleStateChange(id,state){
                table.set();
                $.operation.executionStateChange(id,state)
            },
            //执行修改
            executionStateChange(rows,state){
                const data = table.getData(table.options.id)

                if(!data || !Array.isArray(data)){
                    $.modal.msgError("未知异常，请尝试刷新页面！")
                    return;
                }

                const stateProperty = table.options.state
                const uniqueId = table.options.uniqueId
                const hint = state==state_type.OK.value ? state_type.OK.name:state_type.DISABLE.name

                let ids = [];
                if(Array.isArray(rows)){
                    ids = data.filter((item)=>rows.includes(item[uniqueId]) && item[stateProperty]!=state )
                        .map(item=>item[uniqueId])
                    if(!ids.length){
                        const needlessIds = data.filter((item)=>rows.includes(item[uniqueId]) && item[stateProperty]==state ).map(item=>item[uniqueId])
                        $.modal.alertWarning(`数据标识编号 ${needlessIds} 已经为 ${hint} 无需修改！`);
                        return;
                    }
                }else{
                    ids.push(rows)
                }
                $.modal.confirm(`确认要将标识编号为 "${ids}" 的数据状态设置为 "${hint}" 吗？`,()=>{
                    const updateStateUrl = table.options.updateStateUrl
                    const data = {ids:ids,state:state}
                    $.operation.save($.axiosRequest.put(updateStateUrl,data))
                });
            },
            // 删除信息
            remove: function(id) {
                table.set();
                $.modal.confirm("确定删除该条" + table.options.modalName + "信息吗？", function() {
                    var url = $.common.isEmpty(id) ? table.options.removeUrl : table.options.removeUrl.replace("{id}", id);
                    if(table.options.type == table_type.bootstrapTreeTable) {
                        $.operation.get(url);
                    } else {
                        $.operation.handlerRemove(id);
                    }
                });
            },
            // 批量删除信息
            removeAll: function() {
                table.set();
                var rows = $.common.isEmpty(table.options.uniqueId) ? $.table.selectFirstColumns() : $.table.selectColumns(table.options.uniqueId);
                if (rows.length == 0) {
                    $.modal.alertWarning("请至少选择一条记录");
                    return;
                }
                $.modal.confirm("确认要删除选中的" + rows.length + "条数据吗?", function() {
                    $.operation.handlerRemove(rows.join());
                });
            },
            //处理删除
            handlerRemove(uniqueIds){
                var url = table.options.removeUrl
                $.operation.submitProcess($.axiosRequest.remove(url,uniqueIds))
            },
            //数据恢复
            restoreData:function(id){
                table.set();
                $.operation.handleDataRecovery(id)
            },
            //批量数据恢复
            restoreDataAll:function(){
                table.set();
                var ids = $.common.isEmpty(table.options.uniqueId) ? $.table.selectFirstColumns() : $.table.selectColumns(table.options.uniqueId);
                $.operation.handleDataRecovery(ids)
            },
            //处理数据恢复
            handleDataRecovery:function(ids){
                if (ids.length == 0) {
                    $.modal.alertWarning("请至少选择一条记录");
                    return;
                }
                $.modal.confirm("确认要恢复选中的" + ids.length + "条数据吗?", function() {
                    let url = table.options.restoreDataUrl.replace("{ids}", ids)
                    $.operation.submitProcess($.axiosRequest.put(url))
                });
            },
            exportExcel: function(formId){
                table.set();
                $.modal.confirm("确定导出所有" + table.options.modalName + "吗？", function() {
                    var currentId = $.common.isEmpty(formId) ? $('form').attr('id') : formId;
                    var params = $("#" + table.options.id).bootstrapTable('getOptions');
                    var dataParam = $("#" + currentId).serializeArray();
                    dataParam.push({ "name": "orderByColumn", "value": params.sortName });
                    dataParam.push({ "name": "isAsc", "value": params.sortOrder });
                    $.modal.loading("正在导出数据，请稍候...");
                    $.axiosRequest.post(table.options.exportUrl, $.common.toFormData(dataParam),{headers:contentTypeForm})
                        .then(res=>{
                            window.location.href = ctx + "common/download?fileName=" + encodeURI(res.msg) + "&delete=" + true;
                        })
                });
            },
            // 下载模板
            importTemplate: function() {
                $.operation.download(activeWindow().table.options.importTemplateUrl,{},`${table.options.modalName}_数据模板${new Date().getTime()}.xlsx`)
            },
            // 导入数据
            importExcel: function(formId, width, height) {
                table.set();
                var currentId = $.common.isEmpty(formId) ? 'importTpl' : formId;
                let $currentId = $('#' + currentId)
                let content = $currentId.length>0?$currentId.html():`
                <!-- 导入区域 -->
                    <form enctype="multipart/form-data" class="mt20 mb10">
                        <div class="col-xs-offset-1">
                            <input type="file" id="file" name="file"/>
                            <div class="mt10 pt5">
                            &nbsp;\t<a onclick="$.operation.importTemplate()" class="btn btn-default btn-xs"><i class="fa fa-file-excel-o"></i> 下载模板</a>
                            </div>
                            <font color="red" class="pull-left mt10">
                                提示：仅允许导入“xls”或“xlsx”格式文件！
                            </font>
                        </div>
                    </form>
                `;
                var _width = $.common.isEmpty(width) ? "400" : width;
                var _height = $.common.isEmpty(height) ? "230" : height;

                top.layer.open({
                    type: 1,
                    area: [_width + 'px', _height + 'px'],
                    fix: false,
                    //不固定
                    maxmin: true,
                    shade: 0.3,
                    title: '导入' + table.options.modalName + '数据',
                    content: content,
                    btn: ['<i class="fa fa-check"></i> 导入', '<i class="fa fa-remove"></i> 取消'],
                    // 弹层外区域关闭
                    shadeClose: true,
                    btn1: function(index, layero){
                        var file = layero.find('#file').val();
                        if (file == '' || (!$.common.endWith(file, '.xls') && !$.common.endWith(file, '.xlsx'))){
                            $.modal.msgWarning("请选择后缀为 “xls”或“xlsx”的文件。");
                            return false;
                        }
                        var index = top.layer.load(2, {shade: false});
                        var formData = new FormData(layero.find('form')[0]);

                        $.axiosRequest.post(table.options.importUrl, formData)
                            .then(async (data) => {
                                const resText = await data.text()
                                const rspObj = JSON.parse(resText)
                                $.modal.close(index);
                                $.table.refresh();
                            })
                            .catch((r) => {
                                $.modal.close(index);
                                console.error(r)
                                layero.find('#file').val('');
                            })
                    }
                });
            },
            //判断data 是否为 blob(二进制) 格式
            blobValidate:async function(data) {
                try {
                    const text = await data.text()
                    JSON.parse(text)
                    return false
                } catch (error) {
                    return true
                }
            },
            //下载
            download:function(url, params, filename) {
                openLoadingAndDisableButton()
                return axiosRequest
                    .post(url, params, {
                        transformRequest: [
                            (params) => {
                                return tansParams(params)
                            },
                        ],
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        responseType: 'blob',
                    })
                    .then(async (data) => {

                        closeLoadingAndEnableButton()

                        const isBlob = await $.operation.blobValidate(data)
                        if (isBlob) {
                            const blob = new Blob([data])
                            saveAs(blob, filename)
                        } else {
                            const resText = await data.text()
                            const rspObj = JSON.parse(resText)
                            const errMsg =
                                errorCode[rspObj.code] || rspObj.msg || errorCode['default']
                            $.modal.alertError(errMsg);
                        }
                    })
                    .catch((r) => {
                        closeLoadingAndEnableButton()

                        console.error(r)

                        $.modal.alertError('下载文件出现错误，请联系管理员！');
                    })
            }
            ,//提交后置处理
            submitProcess: function(promise,callback) {
                $.operation.save(promise,callback)
            },
            // 保存信息 刷新表格
            save: function(promise, callback , refreshParent=false) {
                promise.then(res=>{
                    if (typeof callback == "function") {
                        callback(res);
                    }
                    $.operation.successCallback(res,refreshParent);
                }).catch(e=>{
                    //出现错误
                })
            },
            // 成功回调执行事件（父窗体静默更新）
            successCallback: function(result,refreshParent=false) {
                if(refreshParent){
                    var parent = activeWindow();
                    if($.common.isEmpty(parent.table)) {
                        $.modal.msgSuccessReload(result.msg);
                    } else if (parent.table.options.type == table_type.bootstrapTable) {
                        $.modal.close();
                        parent.$.modal.msgSuccess(result.msg);
                        parent.$.table.refresh();
                    } else if (parent.table.options.type == table_type.bootstrapTreeTable) {
                        $.modal.close();
                        parent.$.modal.msgSuccess(result.msg);
                        parent.$.treeTable.refresh();
                    }
                }else{
                    // 保存结果弹出msg刷新table表格
                    if ( table.options.type == table_type.bootstrapTable) {
                        $.modal.msgSuccess(result.msg);
                        $.table.refresh();
                    }
                }
            },
        },
        axiosRequest:{
            getThis(){
                return axiosRequest
            },
            post(url, data,options) {
                return axiosRequest({
                    url: url,
                    method:'post',
                    data:data,
                    ...options,
                })
            }, get(url, params, options) {
                return axiosRequest({
                    url: url,
                    params:params,
                    method:'get',
                })
            }, remove(url, uniqueIds, options) {
                return axiosRequest({
                    url: url +"/"+uniqueIds,
                    method:'delete',
                })
            }, put(url, data, options) {
                return axiosRequest({
                    url: url,
                    method:'put',
                    data:data,
                    ...options,
                })
            },
        },
        logicDelete:{
            //删除 与 未删除 标识切换
            toggle:function(){
                const oldDelFlag = table.options.delFlag
                if(table.options.logicDelete){
                    table.options.delFlag = oldDelFlag == deleteCode.DELETE?deleteCode.NO_DELETE:deleteCode.DELETE
                    $.table.refresh();
                }
            },  //是否标记逻辑删除
            isDelFlag(){
                return table.options.delFlag == deleteCode.DELETE ? true : false
            },
        },
        selectComponent:{
            init(options){
                let key = options.$select[0].name
                let completeOptions ;
                if(select.options.has(key) && select.options.cache){
                    completeOptions = select.options.get(key)
                    if(options.data && options.data instanceof Array && options.data.length>0){
                        completeOptions.data = options.data
                    }
                }else{
                    const defaultOptions = {
                        $select:'',
                        data:[],
                        clear:true, //是否清空原有的select
                        fillDefault:true,//是否填充默认值
                        defaultOption:{name:'请选择',value:''}, //默认的option
                        name:'label',
                        value:'value',
                        selectValue:'',// 默认突出选中的至
                        filter:null,
                        cache:true,//是否缓存
                    }
                    completeOptions = $.extend(defaultOptions,options)
                    if(completeOptions.cache)
                        select.options.set(key,completeOptions)
                }
                $.selectComponent.fillData(completeOptions)
            },fillData(options){
                const $select = options.$select
                let data
                if(options.filter instanceof Function){
                    data = options.filter(options.data)
                }else{
                    data = options.data
                }

                $.selectComponent.clearData(options)

                if(data && data instanceof Array){
                    if(data.length!=1){
                        $.selectComponent.fillDefaultOptions(options)
                    }
                    data.forEach(item=>{
                        $.selectComponent.append($select,item[options.name],item[options.value])
                    })
                }else{
                    $.selectComponent.fillDefaultOptions(options)
                }

                $.selectComponent.selected(options)
            },clearData(options){
                const $select = options.$select
                const clear = options.clear
                if(clear){
                  $select.empty()
                }
            },fillDefaultOptions(options){
                const $select = options.$select
                const fillDefault = options.fillDefault
                const defaultOption = options.defaultOption
                if(fillDefault){
                    $.selectComponent.append($select,defaultOption.name,defaultOption.value)
                }
            },selected(options){
                const $select = options.$select
                const selectValue = options.selectValue
                if(selectValue){
                    $select.find(`option[value=${selectValue}]`).attr('selected',true)
                }
            },append($select,name,value){
                $select.append(`<option value="${value}">${name}</option>`)
            }
        }
    })
})(jQuery);

const contentTypeForm = {'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8'}


const errorCode = {
    '401': '认证失败，无法访问系统资源',
    '403': '当前操作没有权限',
    '404': '访问资源不存在',
    'default': '系统未知错误，请反馈给管理员'
}

function openLoadingAndDisableButton(){
    $.modal.loading("正在处理中，请稍候...");
    $.modal.disable();
}
function closeLoadingAndEnableButton(){
    $.modal.closeLoading();
    $.modal.enable();
}

/**
 * 转json格式
 * @param data
 */
function toJSON(data){
    let json = {};
    if(data instanceof Array && data.length>0){
        const keys = Object.keys(data[0]).toString()
        if(keys === 'name,value'){
            data.forEach(item=>{
                const name = item.name
                const value = item.value
                if(json[name]){
                    json[name] = [json[name],value]
                }else{
                    
                }
            })
        }
    }
}
/**
 * 参数处理
 * @param {*} params  参数
 */
function tansParams(params) {
    let result = ''
    for (const propName of Object.keys(params)) {
        const value = params[propName]
        var part = encodeURIComponent(propName) + '='
        if (value !== null && typeof value !== 'undefined') {
            if (typeof value === 'object') {
                for (const key of Object.keys(value)) {
                    if (value[key] !== null && typeof value[key] !== 'undefined') {
                        let params = propName + '[' + key + ']'
                        var subPart = encodeURIComponent(params) + '='
                        result += subPart + encodeURIComponent(value[key]) + '&'
                    }
                }
            } else {
                result += part + encodeURIComponent(value) + '&'
            }
        }
    }
    return result
}



